package com.sens.orderback;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;

import com.sens.common.Config;
import com.sens.common.LifecycleManage;
import com.sens.common.Log;
import com.sens.common.TimeUtil;
import com.sens.commonui.PermissionUtil;
import com.sens.database.LiteOrmDBUtil;
import com.sens.network.AlipayOrderCallback;
import com.sens.network.ApiByHttp;
import com.sens.network.MybankOrderCallback;
import com.sens.orderback.ui.activity.MainActivity;
import com.sens.orderback.ui.widget.SwipeBackLayout;
import com.sens.tables.AliPayConfig;
import com.sens.tables.AlipayOrder;
import com.sens.tables.CommonConfig;
import com.sens.tables.MybankConfig;
import com.sens.tables.MybankOrder;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class OrderBackApplication extends Application {
    private static OrderBackApplication instance;
    private LifecycleManage lifecycleManage;
    private boolean alipayCollectionAble;
    private boolean mybankCollectionAble;

    public boolean isAlipayCollectionAble() {
        return alipayCollectionAble;
    }

    public void setAlipayCollectionAble(boolean alipayCollectionAble) {
        if (this.alipayCollectionAble == alipayCollectionAble) return;
        this.alipayCollectionAble = alipayCollectionAble;
        AliPayConfig aliPayConfig = LiteOrmDBUtil.getGlobalDBUtil(instance).queryOne(AliPayConfig.class);
        if (aliPayConfig != null) {
            aliPayConfig.setCollectionAble(alipayCollectionAble);
            LiteOrmDBUtil.getGlobalDBUtil(instance).update(aliPayConfig);
        }
    }

    public boolean isMybankCollectionAble() {
        return mybankCollectionAble;
    }

    public void setMybankCollectionAble(boolean mybankCollectionAble) {
        if (this.mybankCollectionAble == mybankCollectionAble) return;
        this.mybankCollectionAble = mybankCollectionAble;
        MybankConfig mybankConfig = LiteOrmDBUtil.getGlobalDBUtil(instance).queryOne(MybankConfig.class);
        if (mybankConfig != null) {
            mybankConfig.setCollectionAble(mybankCollectionAble);
            LiteOrmDBUtil.getGlobalDBUtil(instance).update(mybankConfig);
        }
    }

    public static OrderBackApplication getInstance() {
        return instance;
    }

    private boolean initDatabase = false;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH)
            setTheme(android.R.style.Theme_Material_Light_NoActionBar);
        instance = this;
        Logger.setDebug(Config.ISDEBUG);
        NoHttp.initialize(instance);
        Log.i("OrderBackApplication创建成功");
        lifecycleManage = new LifecycleManage() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                super.onActivityCreated(activity, savedInstanceState);
                if (activity.getClass() == MainActivity.class) return;
                new SwipeBackLayout(activity);
            }
        };
        registerActivityLifecycleCallbacks(lifecycleManage);
        if (PermissionUtil.checkPermission(instance, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            instance.initDatabase();
        }
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public void initDatabase() {
        if (initDatabase) return;
        initDatabase = true;
        LiteOrmDBUtil.getGlobalDBUtil(instance).deleteSmallByTime(AlipayOrder.class, "time", simpleDateFormat.format(TimeUtil.getCompareDate(-5)));
        initConfig();
        if (LiteOrmDBUtil.getGlobalDBUtil(instance).queryCount(AlipayOrder.class, "hasUpload", false) > 0)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<AlipayOrder> alipayOrderList = LiteOrmDBUtil.getGlobalDBUtil(instance).queryByWhere(AlipayOrder.class, "hasUpload", false);
                    for (AlipayOrder alipayOrder : alipayOrderList) {
                        try {
                            long time = simpleDateFormat.parse(alipayOrder.getTime()).getTime();
                            if (System.currentTimeMillis() - time > 24 * 60 * 60 * 1000) continue;
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        ApiByHttp.getInstance().uploadAlipayOrder(alipayOrder, new AlipayOrderCallback(instance, alipayOrder.getTradeNo()));
                    }
                }
            }).start();
        if (LiteOrmDBUtil.getGlobalDBUtil(instance).queryCount(MybankOrder.class, "hasUpload", false) > 0)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<MybankOrder> mybankOrderList = LiteOrmDBUtil.getGlobalDBUtil(instance).queryByWhere(MybankOrder.class, "hasUpload", false);
                    for (MybankOrder mybankOrder : mybankOrderList) {
                        if (System.currentTimeMillis() - mybankOrder.getTime() > 24 * 60 * 60 * 1000)
                            continue;
                        ApiByHttp.getInstance().uploadMybankOrder(mybankOrder, new MybankOrderCallback(instance, mybankOrder.getOrderId()));
                    }
                }
            }).start();
    }

    private void initConfig() {
        CommonConfig commonConfig = LiteOrmDBUtil.getGlobalDBUtil(instance).queryOne(CommonConfig.class);
        if (commonConfig != null) {
            ApiByHttp.getInstance().setHost(commonConfig.getServiceHost());
        } else {
            commonConfig = new CommonConfig();
            LiteOrmDBUtil.getGlobalDBUtil(instance).save(commonConfig);
        }
        AliPayConfig aliPayConfig = LiteOrmDBUtil.getGlobalDBUtil(instance).queryOne(AliPayConfig.class);
        if (aliPayConfig != null) {
            alipayCollectionAble = aliPayConfig.isCollectionAble();
        } else {
            aliPayConfig = new AliPayConfig();
            LiteOrmDBUtil.getGlobalDBUtil(instance).save(aliPayConfig);
        }
        MybankConfig mybankConfig = LiteOrmDBUtil.getGlobalDBUtil(instance).queryOne(MybankConfig.class);
        if (mybankConfig != null) {
            mybankCollectionAble = mybankConfig.isCollectionAble();
            ApiByHttp.getInstance().setChannelNumber(mybankConfig.getChannelNumber());
        } else {
            mybankConfig = new MybankConfig();
            LiteOrmDBUtil.getGlobalDBUtil(instance).save(mybankConfig);
        }
        ApiByHttp.getInstance().setQueryTimeInterval(mybankConfig.getQueryTimeInterval());
    }

    @Override
    public void onTerminate() {
        unregisterActivityLifecycleCallbacks(lifecycleManage);
        super.onTerminate();
    }
}